package classmates

import (
	"crypto/md5"
	"fmt"
	"os"
	"time"

	"github.com/howeyc/gopass"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

type Classmate struct {
	ID        int
	Name      string
	Sn        string
	Sex       string
	Classname string
	Pswd      string
	QQ        string
	Haoma     string
	Money     float32
	Brithday  time.Time
	Email     string
	ClassId   int
}

type Records struct {
	ID         int
	Name       string
	Sn         string
	Comments   string
	Classid    int
	Createtime time.Time
	Tel        string
	Num        int
}

func init() {
	dsn := "root:123456@tcp(172.14.1.68:3306)/classmates?charset=utf8mb4&parseTime=True&loc=Local"
	var err error
	DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		fmt.Println("链接数据库失败，原因是：", err.Error())
		return
	}

	fmt.Println("链接成功", DB)

}

var DB *gorm.DB

func DBDemo() {

	//var zhangsan Classmate
	//zhangsan.Name = "张三"
	//zhangsan.ID = 99
	//zhangsan.Sex = "男"
	//zhangsan.Sn = "123456"
	//tx := DB.Save(&zhangsan)
	//fmt.Println(tx)

	for {
		var lzl Classmate
		var findname string
		fmt.Println("欢迎使用查找软件")
		fmt.Println("请输入您想查询的人")
		fmt.Scanln(&findname)
		DB.Where("name=?", findname).First(&lzl)
		fmt.Println(lzl.Name)
		fmt.Println(lzl.Sn)
		fmt.Println(lzl.Classname)

	}
}

var LoginUser Classmate

func Login() bool {
	var name string
	fmt.Println("请输入用户名")
	fmt.Scanln(&name)
	var pswd string
	fmt.Println("请输入密码")
	pswDBytes, err := gopass.GetPasswdPrompt("密码", true, os.Stdin, os.Stdout)
	if err != nil {
		fmt.Println("GetPasswdPrompt 失败，", err.Error())
		return false
	}
	pswd = string(pswDBytes)
	pswd = fmt.Sprintf("%x", md5.Sum([]byte(pswd)))
	//fmt.Scanln(&pswd)

	DB.Raw("SELECT*FROM classmates.classmates where name=?", name).Scan(&LoginUser)
	if LoginUser.Pswd == pswd {
		fmt.Println("登录成功")
		AutoWriteLog(LoginUser.Name, LoginUser.ID, time.Now(), "登录成功", LoginUser.Sn)
		return true
	} else {
		fmt.Println("登录失败")
		return false
	}

}

// 寻找优秀学员
// func FindTop10() {
// DB.Raw(`SELECT COUNT(*)AS num,name FROM classmates.records GROUP BY(sn) ORDER BY num DESC LIMIT 0,10;`).Scan(&kaoqinList)
//
//		for _, kaoqin := range kaoqinList {
//			fmt.Println(kaoqin.name, "的考勤次数是：", kaoqin.num)
//		}
//	}
//
// 修改密码
func Resetpswd() {
	//先验证当前登陆者的密码。提示用户输入旧密码
	var oldpswd string
	fmt.Println("请输入当前密码进行验证")
	fmt.Scanln(&oldpswd)

	oldpswd = fmt.Sprintf("%x", md5.Sum([]byte(oldpswd)))
	if LoginUser.Pswd != oldpswd {

		fmt.Println("你的密码输入错误")
		return
	}
	//让用户输入新密码
	var newPswd string
	fmt.Println("请输入新密码")
	fmt.Scanln(&newPswd)
	//让用户输入新密码验证
	var newPswdAgain string
	fmt.Println("请再次输入新密码进行验证")
	fmt.Scanln(&newPswdAgain)

	if newPswdAgain != newPswd {
		fmt.Println("两次输入的密码不一致请重试")
		return
	}
	//将新密码存入数据库
	LoginUser.Pswd = fmt.Sprintf("%x", md5.Sum([]byte(newPswd)))
	DB.Save(&LoginUser)
	fmt.Println("修改密码成功")
}

func Jiafen() {

	var name string
	fmt.Println("请输入你要修改考勤的人的姓名")
	fmt.Scanln(&name)
	var beOperSN string
	var recordsList []Records
	DB.Raw("SELECT*from classmates.records where name=?", name).Scan(&recordsList)
	for _, record := range recordsList {

		fmt.Printf("id:%5d| 姓名:%10s|分数:%10v|时间:%20v  \n", record.ID, record.Name, record.Comments, record.Createtime)
		beOperSN = record.Sn
	}

	fmt.Println("请输入考勤的id")
	var recordid int
	fmt.Scanln(&recordid)
	fmt.Println("请输入所加的分数")
	var fenshu string
	fmt.Scanln(&fenshu)
	DB.Exec("update classmates.records set comments=? where id=?", fenshu, recordid)
	fmt.Println("加分成功")
	DB.Raw("SELECT*from classmates.records where name=?", name).Scan(&recordsList)
	for _, record := range recordsList {

		fmt.Printf("id:%5d| 姓名:%10s|分数:%10v|时间:%20v  \n", record.ID, record.Name, record.Comments, record.Createtime)
	}
	AutoWriteLog(LoginUser.Name, LoginUser.ID, time.Now(), "给"+name+"加分"+fenshu, beOperSN)
}

type Logs struct {
	ID          int
	OpName      string
	OpId        int
	Createtime  time.Time
	Content     string
	BeOperateSN string
}

// 日志系统
func AutoWriteLog(opername string, operID int, shijian time.Time, content string, beOPSN string) {

	var thisLog Logs
	thisLog.BeOperateSN = beOPSN
	thisLog.Content = content
	thisLog.OpName = opername
	thisLog.ID = operID
	thisLog.Createtime = shijian
	DB.Save(&thisLog)

}

// 查询考勤前后10位
func Findtop10() {
	var kaoqinlist []*Records
	fmt.Println("考勤前10位是：")
	DB.Raw(`SELECT COUNT(*) AS num,name FROM classmates.records   GROUP BY (sn) ORDER BY num DESC  LIMIT 0,10`).Scan(&kaoqinlist)
	for _, kaoqin := range kaoqinlist {
		fmt.Println(kaoqin.Name, "您的考勤次数为", kaoqin.Num)
	}
	fmt.Println("考勤后10位是：")
	DB.Raw(`SELECT COUNT(*) AS num,name FROM classmates.records   GROUP BY (sn) ORDER BY num ASC  LIMIT 0,10`).Scan(&kaoqinlist)
	for _, kaoqin := range kaoqinlist {
		fmt.Println(kaoqin.Name, "您的考勤次数为", kaoqin.Num)
	}
}

// 生日祝福
//func BrithdayBlessing() {
//用for循环永远不停的查数据库
//	for {
//		//当查到当天的学员后，发送祝福
//		var allTodayStudents []Classmate
//		sqlstr := fmt.Sprintf(`SELECT*FROM classmates.classmates WHERE brithday LIKE'%%-%v-%v-%%'`, int(time.Now().Month()), int(time.Now().Day()))
//		fmt.Println("执行 sql是：", sqlstr)
//		DB.Raw(sqlstr).Scan(&allTodayStudents)
//		var allEmails []string
//		for _, student := range allTodayStudents {
//			allEmails = append(allEmails, student.Email)
//		}
//		fmt.Println("发送了祝福的人", allEmails)
//		email.SendEmail(allEmails, "祝你生日快乐", "放假一起吃饭")
//		fmt.Println("发完了")
//		time.Sleep(time.Hour * 24)
//	}

//}
